package cn.passlink.bletoothchat.BleGATT;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.util.Log;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import cn.passlink.bletoothchat.mActivity.AddFriendsActivity;

@SuppressLint("MissingPermission")

public class ClientUtils {
    private Context context;
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothManager bluetoothManager;
    private BluetoothGatt bluetoothGatt;
    private AddFriendsActivity mAddFriendsActivity;
    //广播发送
    private Intent chngeIntent = new Intent("cn.passlink.setCharacteristicValue_ACTION");//状态更改变化用于判断是服务端还是客户端
    private Intent BleStateIntent = new Intent("BleStateBroadcast");
    private boolean isScanning = false;
    // 服务uuid
    public static  UUID UUID_SERVER = UUID.fromString("0000fff2-0000-1000-8000-00805f9b34fb");
    // 读的特征值
    public static  UUID UUID_CHAR_READ = UUID.fromString("0000ffe3-0000-1000-8000-00805f9b34fb");
    // 写的特征值
    public static  UUID UUID_CHAR_WRITE = UUID.fromString("0000ffe4-0000-1000-8000-00805f9b34fb");
    List<BluetoothDevice> scannedDevices = new ArrayList<>();
    private Handler handler=new Handler();


    public ClientUtils(Context context,AddFriendsActivity mAddFriendsActivity) {
        this.context = context;
        this.bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
        this.bluetoothAdapter = bluetoothManager.getAdapter();
        this.mAddFriendsActivity=mAddFriendsActivity;

    }
    /**
     * 开始扫描设备
     */
    @SuppressLint("MissingPermission")
    public void startScan() {
        if (bluetoothAdapter == null || isScanning) return;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
            if (scanner != null) {
                scanner.startScan(scanCallback);
                isScanning = true;
            }
        } else {
            bluetoothAdapter.startLeScan(leScanCallback);
            isScanning = true;
        }

        // 开启定时任务，在SCAN_PERIOD时间后停止扫描
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                stopScan();
                Log.d("TAG","停止扫描");
            }
        }, 2000);
    }
    public void stopScan() {
        if (bluetoothAdapter == null || !isScanning) return;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
            if (scanner != null) {
                scanner.stopScan(scanCallback);
                isScanning = false;
            }
        } else {
            bluetoothAdapter.stopLeScan(leScanCallback);
            isScanning = false;
        }
    }
    // 扫描的监听回调
    private ScanCallback scanCallback = new ScanCallback() {

        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            BluetoothDevice device = result.getDevice();
            if (!scannedDevices.contains(device)) {
                scannedDevices.add(device);
                //设备扫描结果处理
                mAddFriendsActivity.setMyscannedDevices(scannedDevices);
                Log.d("TAG","正在获取扫描到的设备");
            }
        }

    };

    private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            // device就是周边的设备了
            // 连接到指定设备
            try {
                connectDevice(device);
            }catch (Exception e){
                Log.d("TAG","连接失败！！！！！！，请检查目标是否正确");

            }


        }
    };

    /**
     * 连接指定设备
     *
     * @param device 自动连接设备
     */
    @SuppressLint("MissingPermission")
    public void connectDevice(BluetoothDevice device) {
        bluetoothGatt = device.connectGatt(context, false, bluetoothGattCallback);
    }

    private BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {
        @SuppressLint("MissingPermission")
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            if (newState == BluetoothGatt.STATE_CONNECTED) {
                Log.e("TAG", "onConnectionStateChange 连接成功");
                //修改状态为客户端
                gatt.discoverServices();

                // 创建意图对象
                BleStateIntent.putExtra("message", "200");
                // 发送广播
                context.sendBroadcast(BleStateIntent);

            } else if (newState == BluetoothGatt.STATE_CONNECTING) {
                Log.e("TAG", "onConnectionStateChange 连接中......");
                BleStateIntent.putExtra("message", "100");
                // 发送广播
                context.sendBroadcast(BleStateIntent);

            } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
                Log.e("TAG", "onConnectionStateChange 连接断开");
                BleStateIntent.putExtra("message", "400");
                // 发送广播
                context.sendBroadcast(BleStateIntent);

            } else if (newState == BluetoothGatt.STATE_DISCONNECTING) {
                Log.e("TAG", "onConnectionStateChange 连接断开中......");
                BleStateIntent.putExtra("message", "500");
                // 发送广播
                context.sendBroadcast(BleStateIntent);

            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            // 设置读特征值的监听，接收服务端发送的数据
            // 获取服务和特征值
            // 发起读取请求
            BluetoothGattService service = bluetoothGatt.getService(UUID_SERVER);
            BluetoothGattCharacteristic characteristicRead = service.getCharacteristic(UUID_CHAR_READ);
            @SuppressLint("MissingPermission")
            boolean b = bluetoothGatt.setCharacteristicNotification(characteristicRead, true);
            Log.e("TAG", "onServicesDiscovered 设置通知 " + b);



        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            byte[] data = characteristic.getValue();
            Log.d("TAG","客户端感应到了服务端属性值被修改！！！");
            // 在这里进行进一步的处理，如解析数据、执行操作等
            String dataStr = new String(data, StandardCharsets.UTF_8);
            Log.d("TAG", "完整数据: " + dataStr);
            // 将数据发送给其他组件，通过广播或回调等方式
            Intent intent = new Intent("com.example.ACTION_DATA_RECEIVED");
            intent.putExtra("ReceivedData", dataStr);
            context.sendBroadcast(intent);

        }

    };
    /**
     * 发送数据
     *
     * @param msg 要发送的数据
     */
    @SuppressLint("MissingPermission")
    public void sendData(String msg) {
        // 找到服务
        BluetoothGattService service = bluetoothGatt.getService(UUID_SERVER);
        if(service!=null){
            // 拿到写的特征值
            BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID_CHAR_WRITE);
            bluetoothGatt.setCharacteristicNotification(characteristic, true);

            byte[] dataBytes = msg.getBytes(StandardCharsets.UTF_8);
            characteristic.setValue(dataBytes);
            bluetoothGatt.writeCharacteristic(characteristic);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.e("TAG", "sendData 发送数据成功");
        }
        else {
            Log.e("TAG", "sendData 发送数据失败");
        }

    }



    /**
     * 断开连接
     */
    //写操作
    public void disconnectDevice() {
        if (bluetoothGatt != null) {
            bluetoothGatt.disconnect();
            bluetoothGatt.close();
            bluetoothGatt = null;
            Log.e("TAG", "disconnectDevice 断开连接成功");
        }
    }

    //读操作
    public void writeToFileToSetCharacteristic(String text) {
        // 可选：添加额外的数据到意图中
        chngeIntent.putExtra("changeCharcteristic", text);
        // 发送广播
        context.sendBroadcast(chngeIntent);
    }

    //发送前判断
    public boolean isBluetoothConnected() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
            return true;
        }
        return false;
    }

}





//发送模板


//
//    String msg=SendDate.getText().toString();
//
//                if (msg.length() == 0) {Toast.makeText(mActivity, "字符为空", Toast.LENGTH_SHORT).show();}
//                        else {
//                        if(clientUtils.isBluetoothConnected()){
//
//                        if(mActivity.getisServer()){
//                        try {
//                        clientUtils.writeToFileToSetCharacteristic(msg);
//                        }catch (Exception e){
//                        Toast.makeText(mActivity, "发送失败@！！！！", Toast.LENGTH_SHORT).show();
//                        }
//
//                        }else {
//                        try {
//                        //服务器更改特征值,相当于发送给客户端
//                        clientUtils.sendData(msg);
//                        }catch (Exception e){
//                        Toast.makeText(mActivity, "发送失败@！！！！", Toast.LENGTH_SHORT).show();
//                        }
//
//                        }
//                        MessageEntity message=new MessageEntity();
//                        message.setState(false);
//                        message.setMesssage(msg);
//                        addSendMessage(message);
//                        SendDate.setText("");
//                        }else {
//                        Toast.makeText(mActivity, "蓝牙未连接无法发送", Toast.LENGTH_SHORT).show();
//                        }
//
//                        }
//



